package com.practice.text;

import java.io.IOException;

public class StringAppender {

	public static void main(String[] args) {
		int threadCount = 10;

		//StringBuffer stringBuffer = new StringBuffer();
		StringBuilder stringBuilder = new StringBuilder();

		Appendable appender = stringBuilder;
		Thread[] threads = new Thread[threadCount];

		for (int i = 0; i < threadCount; i++) {
			StringBuilder sb = new StringBuilder();
			for (int j = 0; j < 1000; j++) {
				sb.append(i);
			}
			sb.append("\n");
			String text = sb.toString();
			StringAppenderTask task = new StringAppenderTask(appender, text);
			threads[i] = new Thread(task);
			threads[i].setPriority(i / 2 + 1);
		}

		for (int i = 0; i < threadCount; i++) {
			threads[i].start();
		}

		for (int i = 0; i < threadCount; i++) {
			try {
				threads[i].join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println(appender.toString());
	}

}

class StringAppenderTask implements Runnable {

	private Appendable appender;
	private String text;

	public StringAppenderTask(Appendable appender, String text) {
		this.appender = appender;
		this.text = text;
	}

	@Override
	public void run() {
		try {
			appender.append(text);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
